<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div class="checkPointIds_change_scc">
                    <el-select filterable v-if='role_off' popper-class="xiala_css" @change="checkPointIds_change"
                        collapse-tags collapse-tags-tooltip multiple clearable v-model="checkPointIds"
                        placeholder="请选择客户" style="width: 260px">
                        <template #header>
                            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getCustomerList_list" :key="item.id" :label="item.customerName"
                            :value="item.id" />
                    </el-select>
                    <el-select filterable popper-class="xiala_css" @change="getPipeLineListByCusId_change" collapse-tags
                        collapse-tags-tooltip multiple clearable v-model="getPipeLineListByCusId_value"
                        placeholder="请选择管线" style="width: 260px;margin-left:15px;">
                        <template #header>
                            <el-checkbox v-model="checkAll2" :indeterminate="indeterminate2" @change="handleCheckAll2">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getPipeLineListByCusId_list" :key="item.id" :label="item.pipeLineName"
                            :value="item.id" />
                    </el-select>
                    <el-select filterable popper-class="xiala_css" collapse-tags collapse-tags-tooltip multiple
                        clearable v-model="getCheckPointListByLineId_value" placeholder="请选择监测点"
                        style="width: 260px;margin-left:15px;">
                        <template #header>
                            <el-checkbox v-model="checkAll3" :indeterminate="indeterminate3" @change="handleCheckAll3">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getCheckPointListByLineId_list" :key="item.id"
                            :label="item.checkPointName" :value="item.id" />
                    </el-select>

                    <el-select filterable popper-class="xiala_css" collapse-tags collapse-tags-tooltip multiple
                        clearable v-model="getAlarmName_value" placeholder="请选择警告信息"
                        style="width: 200px;margin-left:15px;">
                        <template #header>
                            <el-checkbox v-model="checkAll4" :indeterminate="indeterminate4" @change="handleCheckAll4">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getAlarmName_list" :key="item.ruleName" :label="item.ruleName"
                            :value="item.ruleName" />
                    </el-select>
                    <el-date-picker popper-class="time_css" style="width: 340px;margin-left:15px;"
                        :default-time="defaultTime" v-model="details_time" type="datetimerange"
                        start-placeholder="选择开始时间" end-placeholder="选择结束时间" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div class="del_btn_Css" style="margin-top:10px;">

                    <el-button v-if='role_off' @click="del_btn" type="danger" icon="DeleteFilled">删除</el-button>
                    <el-button @click="out_btn" type="warning" icon="Promotion">导出</el-button>
                </div>
            </template>
            <div>
                <el-table class="list_data_Css" border @selection-change="selection_change_btn" height="63vh"
                    ref="multipleTableRef" :data="list_data">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list" :key="item.name">
                        <el-table-column v-if="item.enablePinning" :width="item.minWidth" :prop="item.name"
                            :label="item.displayName">

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div class="current_change_btn_css">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.pageNo" v-model:page-size="find_data.pageSize"
                    :page-sizes="[20, 50, 100, 200, 500]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick, markRaw } from 'vue'
import {
    getCustomerList, getPipeLineListByCusId, getCheckPointListByLineId, getKmlcpycAlarmListByPage, getAlarmName,
    deleteKmlcpycAlarm, importErrorCheckPonit
} from '@/api/monitoring_alarms.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { downFiles, } from '@/utils/common.js'

import CircularJSON from 'circular-json'
onMounted(async () => {
    let test_pile_alarm = JSON.parse(localStorage.getItem('test_pile_alarm'))
    if (test_pile_alarm) {

        nuv_off.value = true
        await getAlarmName_api()
        await getCustomerList_api()
        await role_api()
    } else {
        await getAlarmName_api()
        await getCustomerList_api()
        await role_api()
    }



})
let nuv_off = ref(false)
//#region 登录角色判断 
//  
let role_off = ref(true)
let role_id = ref('')
let role_customerId = ref('')
const role_api = () => {
    let luser = JSON.parse(localStorage.getItem('luser'))
    if (luser.loginName != 'admin') {
        role_off.value = false
        role_id.value = luser.id
        role_customerId.value = luser.customerId
        checkPointIds.value = []
        checkPointIds.value.push(role_customerId.value)
        getCustomerList_list.value = []
        getCustomerList_list.value.push(role_customerId.value)
    }
}
// #endregion
const data_list = ref([''])

//#region 搜索
//#region 客户
const getCustomerList_list = ref([])
const checkPointIds = ref([])
const checkAll = ref(false)
const indeterminate = ref(false)
watch(checkPointIds, (val) => {
    getPipeLineListByCusId_value.value = []
    getCheckPointListByLineId_value.value = []
    if (val.length === 0) {
        checkAll.value = false
        indeterminate.value = false
    } else if (val.length === getCustomerList_list.value.length) {
        checkAll.value = true
        indeterminate.value = false
    } else {
        indeterminate.value = true
    }
})
const handleCheckAll = async (val) => {
    getPipeLineListByCusId_value.value = []
    getCheckPointListByLineId_value.value = []
    indeterminate.value = false
    if (val) {
        checkPointIds.value = getCustomerList_list.value.map((_) => _.id)

    } else {
        checkPointIds.value = []
    }
    getCustomerList_api()
}
const checkPointIds_change = async (e) => {
    getPipeLineListByCusId_api()
}
const getCustomerList_api = () => {
    getPipeLineListByCusId_value.value = []
    getCheckPointListByLineId_value.value = []
    getCustomerList({}).then(res => {
        if (res.resultStatus.resultCode == '0000') {
            getCustomerList_list.value = res.value
            setTimeout(() => {
                if (nuv_off.value) {
                    console.log(1)
                    let test_pile_alarm = JSON.parse(localStorage.getItem('test_pile_alarm'))
                    checkPointIds.value = test_pile_alarm.customerIds
                }
                getPipeLineListByCusId_api()
            }, 500)

        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 管线
const getPipeLineListByCusId_list = ref([])
const getPipeLineListByCusId_value = ref([])
const checkAll2 = ref(false)
const indeterminate2 = ref(false)
watch(getPipeLineListByCusId_value, (val) => {
    getCheckPointListByLineId_value.value = []
    if (val.length === 0) {
        checkAll2.value = false
        indeterminate2.value = false
    } else if (val.length === getPipeLineListByCusId_list.value.length) {
        checkAll2.value = true
        indeterminate2.value = false
    } else {
        indeterminate2.value = true
    }
})
const handleCheckAll2 = (val) => {
    getCheckPointListByLineId_value.value = []
    indeterminate2.value = false
    if (val) {
        getPipeLineListByCusId_value.value = getPipeLineListByCusId_list.value.map((_) => _.id)

    } else {
        getPipeLineListByCusId_value.value = []
    }
    getCheckPointListByLineId_api()
}
const getPipeLineListByCusId_change = async (e) => {
    await getCheckPointListByLineId_api()
}
const getPipeLineListByCusId_api = () => {
    getCheckPointListByLineId_value.value = []
    getPipeLineListByCusId(checkPointIds.value.length > 0 ? checkPointIds.value : data_list.value).then(res => {
        if (res.resultStatus.resultCode == '0000') {
            getPipeLineListByCusId_list.value = res.value
            if (nuv_off.value) {

                let test_pile_alarm = JSON.parse(localStorage.getItem('test_pile_alarm'))
                getPipeLineListByCusId_value.value = test_pile_alarm.pipeLineIds


            }
            getCheckPointListByLineId_api()

        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 监测点
const getCheckPointListByLineId_value = ref([])
const getCheckPointListByLineId_list = ref([])
const checkAll3 = ref(false)
const indeterminate3 = ref(false)
watch(getCheckPointListByLineId_value, (val) => {

    if (val.length === 0) {
        checkAll3.value = false
        indeterminate3.value = false
    } else if (val.length === getCheckPointListByLineId_list.value.length) {
        checkAll3.value = true
        indeterminate3.value = false
    } else {
        indeterminate3.value = true
    }
})
const handleCheckAll3 = (val) => {
    indeterminate3.value = false
    if (val) {
        getCheckPointListByLineId_value.value = getCheckPointListByLineId_list.value.map((_) => _.id)

    } else {
        getCheckPointListByLineId_value.value = []
    }
}
const getCheckPointListByLineId_api = () => {
    let ps = {
        deviceType: '1',
        ids: getPipeLineListByCusId_value.value.length > 0 ? getPipeLineListByCusId_value.value : data_list.value
    }



    getCheckPointListByLineId(ps).then(res => {

        if (res.resultStatus.resultCode == '0000') {
            getCheckPointListByLineId_list.value = res.value
            if (nuv_off.value) {
                let test_pile_alarm = JSON.parse(localStorage.getItem('test_pile_alarm'))
                getCheckPointListByLineId_value.value = test_pile_alarm.checkPoints
                getAlarmName_value.value = test_pile_alarm.rules
                details_time.value[1] = test_pile_alarm.endTime

                details_time.value[0] = test_pile_alarm.startTime
                details_time.value = [test_pile_alarm.startTime, test_pile_alarm.endTime]

                nuv_off.value = false
                list_api()
            }


        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 告警信息下拉
const getAlarmName_value = ref([])
const getAlarmName_list = ref([])
const checkAll4 = ref(false)
const indeterminate4 = ref(false)
watch(getAlarmName_value, (val) => {
    if (val.length === 0) {
        checkAll4.value = false
        indeterminate4.value = false
    } else if (val.length === getAlarmName_list.value.length) {
        checkAll4.value = true
        indeterminate4.value = false
    } else {
        indeterminate4.value = true
    }
})
const handleCheckAll4 = (val) => {
    indeterminate4.value = false
    if (val) {
        getAlarmName_value.value = getAlarmName_list.value.map((_) => _.ruleName)

    } else {
        getAlarmName_value.value = []
    }
}
const getAlarmName_api = () => {
    getAlarmName({}).then(res => {
        getAlarmName_list.value = res.value
    })
}
//#endregion

//#region 时间
// 获取今天的年月日
const getCurrentDateTime = () => {
    let currentDate = new Date();

    // 获取当前日期的时间戳（以毫秒为单位）
    let timestamp = currentDate.getTime();

    // 计算昨天的时间戳
    let yesterdayTimestamp = timestamp - (24 * 60 * 60 * 1000);

    // 使用昨天的时间戳创建日期对象
    let yesterdayDate = new Date(yesterdayTimestamp);

    // 从昨天的日期对象中提取年、月、日、小时、分钟和秒
    let year = yesterdayDate.getFullYear();
    let month = String(yesterdayDate.getMonth() + 1).padStart(2, '0');
    let day = String(yesterdayDate.getDate()).padStart(2, '0');

    // 构建格式为 "YYYY-MM-DD HH:mm:ss" 的昨天时间字符串
    let yesterdayTime = `${year}-${month}-${day}`;
    return yesterdayTime;
}
const getCurrentDateTime2 = () => {
    let now = new Date();

    let year = now.getFullYear().toString().padStart(4, '0');
    let month = (now.getMonth() + 1).toString().padStart(2, '0');
    let day = now.getDate().toString().padStart(2, '0');
    let hours = now.getHours().toString().padStart(2, '0');
    let minutes = now.getMinutes().toString().padStart(2, '0');
    let seconds = now.getSeconds().toString().padStart(2, '0');

    let dateTimeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return dateTimeString;
}

const time1 = ref(getCurrentDateTime() + ' ' + '00:00:00')
const time2 = ref(getCurrentDateTime2())
const defaultTime = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
]
const details_time = ref([time1.value, time2.value])
//#endregion

const search_btn = () => {

    list_api()
}

//#endregion

//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    pageNo: 1,
    pageSize: 20,
    checkPoints: [],
    customerIds: [],
    pipeLineIds: [],
    startTime: "",
    endTime: "",
    rules: [],

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.pageNo = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {
    if (checkPointIds.value.length <= 0) {
        return ElMessage({
            message: '请选择客户！',
            type: 'warning',
        })
    } else if (getPipeLineListByCusId_value.value.length <= 0) {
        console.log(1, getPipeLineListByCusId_value.value)
        return ElMessage({
            message: '请选择管线！',
            type: 'warning',
        })
    } else if (getCheckPointListByLineId_value.value.length <= 0) {
        console.log(2, getCheckPointListByLineId_value.value)
        return ElMessage({
            message: '请选择监测点！',
            type: 'warning',
        })
    } else if (!details_time.value) {
        return ElMessage({
            message: '请选择时间！',
            type: 'warning',
        })
    }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    find_data.checkPoints = getCheckPointListByLineId_value.value,
        find_data.customerIds = checkPointIds.value,
        find_data.pipeLineIds = getPipeLineListByCusId_value.value,
        find_data.rules = getAlarmName_value.value,
        find_data.startTime = details_time.value[0],
        find_data.endTime = details_time.value[1],
        // localStorage.setItem('test_pile_alarm', CircularJSON.stringify(find_data))
        getKmlcpycAlarmListByPage(find_data).then(res => {
            loading.close()
            if (res.resultStatus.resultCode == '0000') {
                list_data.value = res.value.list
                total.value = res.value.total
            } else {
                return ElMessage({
                    message: res.resultStatus.resultMessage,
                    type: 'warning',
                })
            }

        })
}
//#endregion

//#region 表格数据处理
const table_data_list = reactive([
    { name: 'terminalNumber', displayName: '终端编号', minWidth: 150, enablePinning: true },
    { name: 'checkPointName', displayName: '终端名称', minWidth: 200, enablePinning: true },
    { name: 'rules', displayName: '告警信息', minWidth: 200, enablePinning: true },
    { name: 'sampTime', displayName: '采样时间', minWidth: 150, enablePinning: true },
    { name: 'receiveTime', displayName: '接收时间', minWidth: 200, enablePinning: true },
    { name: 'batVoltage', displayName: '电池电压/V', minWidth: 100, enablePinning: true },
    { name: 'onPotential', displayName: '通电电位/V', minWidth: 100, enablePinning: true },
    { name: 'offPotential', displayName: '断电电位/V', minWidth: 100, enablePinning: true },
    { name: 'acPotential', displayName: '交流杂散电压/V', minWidth: 200, enablePinning: true },
    { name: 'selfPotential', displayName: '自然电位/V', minWidth: 100, enablePinning: true },
    { name: 'pointOffset', displayName: '电位极化值/V', minWidth: 120, enablePinning: true },
    { name: 'gradedPotential', displayName: '牺牲阳极输出电流/V', minWidth: 100, enablePinning: true },
    { name: 'humidity', displayName: '湿度/%', minWidth: 100, enablePinning: true },
    { name: 'temperature', displayName: '温度/℃', minWidth: 100, enablePinning: true },
    { name: 'rssi', displayName: '信号强度', minWidth: 100, enablePinning: true },
    { name: 'soilPH', displayName: '土壤PH', minWidth: 100, enablePinning: true },
    { name: 'soilResistivity', displayName: '土壤电阻率/Ω*m', minWidth: 150, enablePinning: true },
    { name: 'erExchangeVoltageA', displayName: 'ER探头1交流杂散电压/V', minWidth: 200, enablePinning: true },
    { name: 'erExchangeVoltageB', displayName: 'ER探头2交流杂散电压/V', minWidth: 200, enablePinning: true },
    { name: 'erExchangeCurrentA', displayName: 'ER探头1交流杂散电流/mA', minWidth: 200, enablePinning: true },
    { name: 'erExchangeCurrentB', displayName: 'ER探头2交流杂散电流/mA', minWidth: 200, enablePinning: true },
    { name: 'erDirectCurrentA', displayName: 'ER探头1直流电流/mA', minWidth: 180, enablePinning: true },
    { name: 'erDirectCurrentB', displayName: 'ER探头2直流电流/mA', minWidth: 180, enablePinning: true },
    { name: 'erExchangeCurrentADensity', displayName: 'ER探头1交流杂散电流密度/A/m² ', minWidth: 250, enablePinning: true },
    { name: 'erExchangeCurrentBDensity', displayName: 'ER探头2交流杂散电流密度/A/m² ', minWidth: 250, enablePinning: true },
    { name: 'erDirectCurrentADensity', displayName: 'ER探头1直流电流密度/A/m² ', minWidth: 250, enablePinning: true },
    { name: 'erDirectCurrentBDensity', displayName: 'ER探头2直流电流密度/A/m² ', minWidth: 250, enablePinning: true },
    { name: 'erProbeResistanceA', displayName: 'ER探头1电阻/mΩ', minWidth: 200, enablePinning: true },
    { name: 'erProbeResistanceB', displayName: 'ER探头2电阻/mΩ', minWidth: 200, enablePinning: true },
    { name: 'erTestPieceOutageA', displayName: 'ER探头1极化电位/V', minWidth: 200, enablePinning: true },
    { name: 'erTestPieceOutageB', displayName: 'ER探头2极化电位/V', minWidth: 200, enablePinning: true },
    { name: 'erCorBatVol', displayName: 'ER腐蚀仪电池电压/V', minWidth: 180, enablePinning: true },
    { name: 'erTestPieceThickA', displayName: 'ER试片1厚度/um', minWidth: 150, enablePinning: true },
    { name: 'erTestPieceThickB', displayName: 'ER试片2厚度/um', minWidth: 150, enablePinning: true },
    { name: 'erProbeResistanceCorRateA', displayName: 'ER探头1土壤腐蚀率/um/年', minWidth: 200, enablePinning: true },
    { name: 'erProbeResistanceCorRateB', displayName: 'ER探头2土壤腐蚀率/um/年', minWidth: 200, enablePinning: true },
])




//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion

//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '是否确认删除该数据?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            let ps = []
            for (let i = 0; i < table_list.value.length; i++) {
                ps.push(table_list.value[i].id)
            }
            deleteKmlcpycAlarm(ps).then(res => {
                if (res.resultStatus.resultCode == '0000') {
                    list_api()
                    return ElMessage({
                        message: res.resultStatus.resultMessage,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.resultStatus.resultMessage,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 导出
const out_btn = () => {
    if (checkPointIds.value.length <= 0) {
        return ElMessage({
            message: '请选择客户！',
            type: 'warning',
        })
    } else if (getPipeLineListByCusId_value.value.length <= 0) {
        console.log(1, getPipeLineListByCusId_value.value)
        return ElMessage({
            message: '请选择管线！',
            type: 'warning',
        })
    } else if (getCheckPointListByLineId_value.value.length <= 0) {
        console.log(2, getCheckPointListByLineId_value.value)
        return ElMessage({
            message: '请选择监测点！',
            type: 'warning',
        })
    } else if (!details_time.value) {
        return ElMessage({
            message: '请选择时间！',
            type: 'warning',
        })
    }

    let thName = []
    for (let i = 0; i < table_data_list.length; i++) {
        if (table_data_list[i].enablePinning == true) {
            thName.push(table_data_list[i].displayName)
        }

    }
    let ps = {
        checkPoints: getCheckPointListByLineId_value.value,
        customerIds: checkPointIds.value,
        pipeLineIds: getPipeLineListByCusId_value.value,
        startTime: details_time.value[0],
        endTime: details_time.value[1],
        rules: getAlarmName_value.value,
        thName: '',
    }
    ps.thName = thName.join(',');
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    importErrorCheckPonit(ps).then(res => {
        loading.close()
        downFiles(res, '测试桩告警')



    })


}
//#endregion

</script>

<style scoped lang='scss'>
.del_btn_Css {
    margin-top: 10px;
}

.list_data_Css {
    width: 100%
}

.current_change_btn_css {
    margin-top: 20px
}


.map_input {
    width: 100%;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.div_bg:hover {
    background-color: darkgray;
}
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}
</style>
